import { store } from '@/store/setup'
import { piniaOidcCreateStoreModule } from 'pinia-oidc'
import { getOidcClientSettings } from './oidcConfig'

import { defineStore } from 'pinia'
import { useUserStoreWithOut } from '@/store'

//创建oidc储存
export const useOidcStore = defineStore(
  piniaOidcCreateStoreModule(
    getOidcClientSettings(),
    {
      // namespaced: true,
      dispatchEventsOnWindow: true,
    },
    // Optional OIDC event listeners
    {
      userLoaded: (user) => {
        // @ts-ignore
        const userStore = useUserStoreWithOut()
        userStore.setToken(user.access_token)
      },
      userUnloaded: () => {
        console.log('OIDC user is unloaded')
        const userStore = useUserStoreWithOut()
        userStore.removeToken()
        userStore.removeTenantId()
      },
      accessTokenExpiring: () => console.log('Access token will expire'),
      accessTokenExpired: () => console.log('Access token did expire'),
      silentRenewError: () => console.log('OIDC user is unloaded'),
      userSignedOut: () => console.log('OIDC user is signed out'),
      oidcError: (payload) => console.log('OIDC error', payload),
      automaticSilentRenewError: (payload) =>
        console.log('OIDC automaticSilentRenewError', payload),
    }
  )
)

// Need to be used outside the setup
export function useOidcStoreWithOut() {
  return useOidcStore(store)
}
